<template>
  <div class="card amap-example">
    <div>
      <div>
        <p>传入默认地址，获取经纬度</p>
        <el-button @click="handlerLngLat">获取</el-button>
        <div>
          <p>默认地址：{{ defaultAddress }}</p>
          <p>经度：{{ defaultLng }}</p>
          <p>纬度：{{ defaultLat }}</p>
        </div>
      </div>
      <hr />
      <div>
        <p>选择点位后，获取详细地址</p>
        <el-button @click="handlerSure">确认</el-button>
        <div>
          <p>详细地址：{{ formattedAddress }}</p>
          <p>经度：{{ lng }}</p>
          <p>纬度：{{ lat }}</p>
        </div>
      </div>
    </div>
    <div class="amap-explore">
      <AmapUI ref="amapUIRef" :opts="opts" :modules="modules" />
    </div>
  </div>
</template>

<script setup lang="ts" name="amapExample">
import { ref, reactive, onMounted } from "vue";
import AmapUI from "@/components/AmapUI/index.vue";
import type { AmapModulesOptions, MapBaseOptions } from "@/components/AmapUI/types";

// 地图配置
const opts = reactive<MapBaseOptions>({
  center: [116.397428, 39.90923],
  zoom: 4
});

const modules = ref<AmapModulesOptions[]>([
  {
    name: "Geocoder",
    markers: {
      city: "石家庄"
    },
    extra: {
      reverseGeocoding: true
    }
  }
]);

// 默认地址与经纬度
const defaultAddress = ref("河北省石家庄市长安区谈固街道白佛小区(中山东路)");
const defaultLng = ref("");
const defaultLat = ref("");

const handlerLngLat = async () => {
  const GeoCoder = amapUIRef.value?.getModule("Geocoder");
  console.log(GeoCoder, "GeoCoder");
  if (!GeoCoder) {
    return;
  }

  // moduleFactory 模块工厂
  const result = await GeoCoder?.moduleFactory?.getLocation(defaultAddress.value.trim());
  defaultLng.value = result?.geocodes?.[0]?.location?.getLng();
  defaultLat.value = result?.geocodes?.[0]?.location?.getLat();
};

// 选择点位后，获取详细地址与经纬度
const formattedAddress = ref("");
const lng = ref("");
const lat = ref("");

// 地图实例
const amapUIRef = ref<InstanceType<typeof AmapUI> | null>(null);
const handlerSure = () => {
  const GeoCoder = amapUIRef.value?.getModule("Geocoder");
  console.log(GeoCoder, "GeoCoder2");

  if (!GeoCoder) {
    return;
  }
  // moduleInstance 模块实例
  formattedAddress.value = GeoCoder?.moduleInstance?.events.getAddress()?.regeocode?.formattedAddress;

  const LngLat = GeoCoder.moduleInstance?.events.getLnglat() || [];
  lng.value = LngLat?.[0];
  lat.value = LngLat?.[1];
};

onMounted(async () => {
  await handlerLngLat();
});
</script>
<style lang="scss" scoped>
.amap-example {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 100%;
}
.amap-explore {
  width: calc(100% - 200px);
  height: 100%;
}
</style>
